package week4;

import jsjf.exceptions.ElementNotFoundException;

import java.util.Arrays;

public class ArrayUnorderedList<T> extends ArrayList<T> implements UnorderedListADT<T> {
    public ArrayUnorderedList() {
        super();
    }

    public ArrayUnorderedList(int initialCapacity) {
        super(initialCapacity);
    }

    @Override
    public void addToFront(T element) {
        // 对数组进行扩容
        if (size() == list.length) {
            expandCapacity();
        }
        int scan = 0;
        // 将现有元素向上移动1个
        for (int shift=rear; shift > scan; shift--) {
            list[shift] = list[shift - 1];
        }
        // 插入元素
        list[scan] = element;
        rear++;
        modCount++;
    }

    @Override
    public void addToRear(T element) {
        if (size() == list.length) {
            expandCapacity();
        }
        list[rear] = element;
        rear++;
        modCount++;
    }

    @Override
    public void addAfter(T element, T target) {
        if (size() == list.length) {
            expandCapacity();
        }
        int scan = 0;

        // 查找插入位置
        while (scan < rear && !target.equals(list[scan])) {
            scan++;
        }
        if (scan == rear) {
            throw new ElementNotFoundException("UnorderedList");
        }
        scan++;

        // 将现有元素向上移动1个
        for (int shift=rear; shift > scan; shift--) {
            list[shift] = list[shift - 1];
        }
        // 插入元素
        list[scan] = element;
        rear++;
        modCount++;
    }

    private void expandCapacity()
    {
        list = Arrays.copyOf(list, list.length * 2);
    }
}
